package com.seu.nic.component.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
public class EchoHandler extends SimpleChannelInboundHandler<String> {

    // 保存所有连接的客户端Channel
    private static final ConcurrentMap<String, Channel> clients =
            new ConcurrentHashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String clientId = ctx.channel().id().asShortText();
        clients.put(clientId, ctx.channel());
        log.info("客户端连接: " + clientId);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.info("Received: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(ExceptionUtils.getFullStackTrace(cause));
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.info("EchoHandler added to pipeline");
        ctx.pipeline().names().forEach(log::info); // 打印pipeline结构
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        String clientId = ctx.channel().id().asShortText();
        clients.remove(clientId);
        log.info("客户端断开: " + clientId);
    }

    // 向指定客户端发送消息
    public static void sendToClient(String clientId, String message) {
        Channel channel = clients.get(clientId);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message + "\n"); // 添加换行符（需与解码器匹配）
        }
    }

    // 广播消息给所有客户端
    public static void broadcast(String message) {
        clients.values().stream()
                .filter(Channel::isActive)
                .forEach(ch -> ch.writeAndFlush(message + "\n"));
    }
}